	SUBROUTINE GETTAGRE ( LUNIT, TAGI, NTAGI, TAGRE, NTAGRE, IRET )

C$$$  SUBPROGRAM DOCUMENTATION BLOCK
C
C SUBPROGRAM:    GETTAGRE
C   PRGMMR: J. ATOR          ORG: NP12       DATE: 2016-06-07
C
C ABSTRACT:  GIVEN A MNEMONIC WITHIN A SUBSET CURRENTLY OPEN FOR
C   READING, THIS SUBROUTINE CHECKS WHETHER THE MNEMONIC REFERENCES
C   ANOTHER ELEMENT WITHIN THE SAME SUBSET VIA AN INTERNAL BITMAP, AND
C   IF SO RETURNS THE REFERENCED MNEMONIC AND ITS LOCATION.  IF THERE
C   IS MORE THAN ONE OCCURRENCE OF THE INPUT MNEMONIC WITHIN THE OVERALL
C   SUBSET DEFINITION, THE SUBROUTINE WILL RETURN THE MNEMONIC REFERRED
C   TO BY THE (NTAGI)th OCCURRENCE OF THE INPUT MNEMONIC, COUNTING FROM
C   THE BEGINNING OF THE OVERALL SUBSET DEFINITION.  A SUBSET DEFINITION
C   MUST ALREADY BE IN SCOPE, EITHER VIA A PREVIOUS CALL TO BUFR ARCHIVE
C   LIBRARY SUBROUTINE READSB OR EQUIVALENT.
C
C PROGRAM HISTORY LOG:
C 2016-06-07  J. ATOR    -- ORIGINAL AUTHOR
C
C USAGE:    CALL GETTAGRE (LUNIT, TAGI, NTAGI, TAGRE, NTAGRE, IRET)
C   INPUT ARGUMENT LIST:
C     LUNIT    - INTEGER: FORTRAN LOGICAL UNIT NUMBER FOR BUFR FILE
C     TAGI     - CHARACTER*(*): MNEMONIC
C     NTAGI    - INTEGER: ORDINAL OCCURRENCE OF TAGI FOR WHICH TAGRE
C                IS TO BE RETURNED, COUNTING FROM THE BEGINNING OF
C                THE OVERALL SUBSET DEFINITION
C
C   OUTPUT ARGUMENT LIST:
C     TAGRE    - CHARACTER*(*): MNEMONIC REFERRED TO BY TAGI VIA AN
C                INTERNAL BITMAP
C     NTAGRE   - INTEGER: ORDINAL OCCURRENCE OF TAGRE REFERRED TO BY
C                (NTAGI)th OCCURRENCE OF TAGI, COUNTING FROM THE
C                BEGINNING OF THE OVERALL SUBSET DEFINITIION.
C     IRET     - INTEGER: RETURN CODE
C                   0 = NORMAL RETURN
C                  -1 = COULD NOT FIND TAGRE
C
C REMARKS:
C    THIS ROUTINE CALLS:        FSTAG    STATUS   STRSUC
C    THIS ROUTINE IS CALLED BY: None
C                               Normally called only by application
C                               programs
C
C ATTRIBUTES:
C   LANGUAGE: FORTRAN 77
C   MACHINE:  PORTABLE TO ALL PLATFORMS
C
C$$$

	USE MODA_USRINT
	USE MODA_MSGCWD
	USE MODA_TABLES

	INCLUDE 'bufrlib.prm'

	CHARACTER*(*) TAGI, TAGRE

	CHARACTER*10 TAGTMP

C----------------------------------------------------------------------
C----------------------------------------------------------------------

	IRET = -1

C	Get LUN from LUNIT.

	CALL STATUS( LUNIT, LUN, IL, IM )
	IF ( IL .EQ. 0 ) RETURN
	IF ( INODE(LUN) .NE. INV(1,LUN) ) RETURN

C	Get TAGRE and NTAGRE from the (NTAGI)th occurrence of TAGI.

	CALL FSTAG( LUN, TAGI, NTAGI, 1, NI, IRET )
	IF ( IRET .NE. 0 ) RETURN
	NRE = NRFELM(NI,LUN)
	IF ( NRE .GT. 0 ) THEN
	    IRET = 0
	    TAGRE = TAG(INV(NRE,LUN))
	    CALL STRSUC( TAGRE, TAGTMP, LTRE )
	    NTAGRE = 0
	    DO II = 1, NRE
		IF ( TAG(INV(II,LUN))(1:LTRE) .EQ. TAGRE(1:LTRE) ) THEN
		  NTAGRE = NTAGRE + 1
		END IF
	    END DO
	END IF

	RETURN
	END
